package com.client.view;

import com.util.JDBCUtils;

import javax.swing.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/***聊天记录页面：
 * @author lyh
 * @date 2021/10/6
 * 记录用户的聊天记录
 *
 */
public class RecordFrame extends JFrame {
    JFrame parent;
    JTextArea jta;
    JScrollPane jsp;
    JPanel jp;
    String ownId;
    String friendId;

    Connection conn;
    PreparedStatement ps;

    public RecordFrame(JFrame parent,String ownId,String friendId) throws Exception {
        this.parent=parent;
        this.ownId=ownId;
        this.friendId=friendId;

        jta=new JTextArea();
        jta.setEditable(false);     //不可编辑
        jsp=new JScrollPane(jta);   //嵌入滚动条
        jp=new JPanel();            //暂时不需要该容器，后续可以在此新建按日期查找功能

        this.setTitle(ownId+"与"+friendId+"的聊天记录");
        this.add(jsp);
        this.setSize(800,400);
        this.setDefaultCloseOperation(HIDE_ON_CLOSE);
        this.setLocationRelativeTo(parent);
        this.setVisible(true);

        performRecord();
    }

    /***显示聊天记录：
     *
     */
    public void performRecord() throws Exception {
        conn= JDBCUtils.getConnection();

        String sql="select * from sys.message where sender=? or sender=?";

        ps=conn.prepareStatement(sql);

        ps.setString(1,ownId);
        ps.setString(2,friendId);

        ResultSet result=ps.executeQuery();
        //遍历循环取出每一条当前聊天者的信息
        while (result.next()){
            //将查询结果写入文本域
            String text="消息时间:"+result.getString("sendTime")
                    +System.lineSeparator()
                    +result.getString("sender")+"--->"+result.getString("getter")
                    +System.lineSeparator()     //换行
                    +result.getString("text")
                    +System.lineSeparator();    //换行
            jta.append(text);
        }
    }
}
